<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSVToJSON</title>
</head>

<body>
    <p id="res"></p>
    <script>
        const CSVToJSON = (str, delimiter = ',') => {
            const titles = str.slice(0, str.indexOf('\n')).split(delimiter);
            return str
                .slice(str.indexOf('\n') + 1)
                .split('\n')
                .map(v => {
                    const values = v.split(delimiter);
                    return titles.reduce(
                        (obj, title, index) => ((obj[title] = values[index]), obj),
                        {}
                    );
                });
        };

        const res = document.getElementById('res');
        res.innerHTML = `CSVToJSON('col1,col2\na,b\nc,d');的结果是:${JSON.stringify(CSVToJSON('col1,col2\na,b\nc,d'))}`;
    </script>
</body>

</html>